package cn.gs.system.controller;

import cn.gs.common.dto.R;
import cn.gs.common.enums.StatusEnums;
import cn.gs.common.exception.GlobalException;
import cn.gs.common.utils.vcode.Captcha;
import cn.gs.common.utils.vcode.GifCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author gs
 * @date 2020/1/9
 */
@RestController
@Slf4j
public class LoginController {

    @GetMapping("/gifCode")
    public String getCode(HttpServletResponse response, HttpServletRequest request) {
        try {
            HttpSession session = request.getSession(true);
            session.removeAttribute("gifCode");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Expires", "0");
            response.setContentType("image/gif");
            Captcha captcha = new GifCaptcha(146, 33, 4);
            captcha.out(response.getOutputStream());
            session.setAttribute("gifCode", captcha.text().toLowerCase());
            return captcha.text().toLowerCase();
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException("验证码错误");
        }
    }

    @PostMapping("/login")
    public R login(String username, String password, String code, Boolean remember){
        if(StringUtils.isEmpty(code)){
            return new R(StatusEnums.CODE_ERROR);
        }
        Subject subject = SecurityUtils.getSubject();
        String gifCode = (String)subject.getSession().getAttribute("gifCode");
        if(!code.equalsIgnoreCase(gifCode)){
            return new R(StatusEnums.CODE_ERROR);
        }

        UsernamePasswordToken token = new UsernamePasswordToken(username, password, remember);

        try {
            subject.login(token);
            return new R(StatusEnums.SUCCESS);
        }catch (Exception e){
            log.error(e.getMessage());
            throw new UnknownAccountException(e.getMessage());
        }

    }


}
